package com.zhouz.admin.app.aop;


import com.zhouz.admin.app.db.exception.ReSubmitException;
import com.zhouz.admin.app.jwt.JwtHelper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Order(0)
public class ReSubmitAop {

    @Autowired
    public HttpServletRequest request;
    @Autowired
    public RedisTemplate redisTemplate;

    @Pointcut("@annotation(reSubmitAnno)")
    public void initLogAnno(ReSubmitAnno reSubmitAnno) {
    }
    @Before("initLogAnno(reSubmitAnno)")
    public void doBefore(JoinPoint point, ReSubmitAnno reSubmitAnno) {
        String token = null;
        if(reSubmitAnno.admin()){
            token = request.getHeader("X-Litemall-Admin-Token");
        }else{
             token = request.getHeader(JwtHelper.LOGIN_TOKEN_KEY);
        }

        if (token == null || token.isEmpty()) {
            token = request.getRemoteAddr() + request.getQueryString();
            //throw new NoLoginException();
        }
        String key = reSubmitAnno.value() + ":" + token;
        boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", reSubmitAnno.times(), TimeUnit.SECONDS);
        if (!flag) {
            throw new ReSubmitException();
        }
    }
//    @Around("initLogAnno(reSubmitAnno)")
//    public Object doController(ProceedingJoinPoint point,ReSubmitAnno reSubmitAnno) throws Exception {
//        String token = request.getHeader(JwtHelper.LOGIN_TOKEN_KEY);
//        if (token == null || token.isEmpty()) {
//            throw new NoLoginException();
//        }
//        try {
//            String key = reSubmitAnno.value()+":"+token;
//            boolean flag = redisTemplate.opsForValue().setIfAbsent(key,"1",reSubmitAnno.times(), TimeUnit.SECONDS);
//            if(!flag){
//                return Result.badbusy();
//            }
//            return point.proceed();
//        } catch (Throwable throwable) {
//            throwable.printStackTrace();
//            throw throwable;
//        }
//    }
}
